package org.little.beans.factory.annotation;

import org.little.beans.factory.BeanCreationException;
import org.little.beans.factory.config.AutowireCapableBeanFactory;
import org.little.beans.factory.config.DependencyDescriptor;
import org.little.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @author Tinyspot
 * @date 2022-05-25 21:51
 */
public class AutowiredFiledElement extends InjectionElement {

    boolean required;

    public AutowiredFiledElement(Field field, boolean required, AutowireCapableBeanFactory factory) {
        super(field, factory);
        this.required = required;
    }

    public Field getFiled() {
        return (Field) this.member;
    }

    @Override
    public void inject(Object target) {
        Field filed = this.getFiled();
        try {
            DependencyDescriptor descriptor = new DependencyDescriptor(filed, this.required);
            Object value = factory.resolveDependency(descriptor);
            if (value != null) {
                ReflectionUtils.makeAccessible(filed);
                filed.set(target, value);
            }
        } catch (Throwable throwable) {
            throw new BeanCreationException("Could not autowire field: " + filed, throwable);
        }
    }
}
